package com.umakr.springboot.controller;

import com.umakr.springboot.entity.User;
import com.umakr.springboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * Created by Mikey on 2016/11/8.
 */
@Controller
public class indexController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping("/getUser.json")
    @ResponseBody
    public List<User> getUser(){
//        PageRequest pageRequest = new PageRequest(page,rows);
        List<User> users = userRepository.findAll();
        return users;
    }

    @RequestMapping("/saveUser.json")
    @ResponseBody
    public Map saveUser(User user){
        Map map = new HashMap();
        if(user.getId() == null||"".equals(user.getId())){
            user.setId(UUID.randomUUID().toString());
            userRepository.saveAndFlush(user);
            map.put("success","添加成功");
        }else{
            User user1 = userRepository.findOne(user.getId());
            user1.setName(user.getName());
            user1.setAge(user.getAge());
            userRepository.saveAndFlush(user1);
            map.put("success","修改成功");
        }
        return map;
    }

    @RequestMapping("/deleteUser.json")
    @ResponseBody
    public String deleteUser(String id){
        String map;
        userRepository.delete(id);
        map = "删除成功";
        return map;
    }
}
